package org.redis.cluster.admin.server.service;

import java.util.Collection;

import org.apache.commons.collections.CollectionUtils;
import org.redis.cluster.admin.client.factory.RedisClientFactory;
import org.redis.cluster.config.ClientConfig;
import org.redis.cluster.config.ServerConfig;
import org.redis.cluster.registry.Registry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import redis.clients.jedis.Jedis;

@Service
public class ServerService {
	
	protected final Logger logger=LoggerFactory.getLogger(getClass());
	
	@Autowired
	private Registry registry;
	@Autowired
	private RedisClientFactory redisClientFactory;
	
	/**
	 * 返回服务
	 * @return
	 */
	public Collection<ServerConfig> getServers() {
		return registry.getServers();
	}
	
	/**
	 * 返回服务
	 * @param id
	 * @return
	 */
	public ServerConfig getServer(String id) {
		Collection<ServerConfig> configs=getServers();
		if(CollectionUtils.isEmpty(configs)) {
			return null;
		}
		
		for(ServerConfig config:configs) {
			if(!config.getId().equals(id)) {
				continue;
			}
			
			return config;
		}
		
		return null;
	}
	
	/**
	 * @param id
	 * @return
	 */
	public String getInfo(String id) {
		ServerConfig config=getServer(id);
		if(config==null) {
			return null;
		}
		
		return getInfo(config);
	}

	/**
	 * info
	 * @param serverConfig
	 * @return
	 */
	public String getInfo(ServerConfig serverConfig) {
		ClientConfig config=new ClientConfig();
		config.setHost(serverConfig.getHost());
		config.setPort(serverConfig.getPort());
		
		Jedis jedis=redisClientFactory.getClient(config);
		
		try {
			return jedis.info();
		}
		finally {
			try {
				redisClientFactory.returnClient(config, jedis);
			}
			catch(Exception e) {
				if(logger.isErrorEnabled()) {
					logger.error("",e);
				}
			}
		}
	}
}